package com.atguigu.gulimall.product.exception.advice;


import com.atguigu.common.utils.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;


/**
 * 集中处理所有的异常
 */

@Slf4j   // 只要标记了@Controller @RestController 的类抛出的异常，都要捕获
//@ControllerAdvice(basePackageClasses = {Controller.class, RestController.class})
public class ExceptionHandlerAdvice {

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResult handleValidException(MethodArgumentNotValidException e) {

        log.error("数据校验出现问题: {},异常类型: {}", e.getMessage(), e.getClass());

        BindingResult bindingResult = e.getBindingResult();

        Map<String, String> errorMap = new HashMap<>();

        bindingResult.getFieldErrors().forEach((fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }));

        return BaseResult.error(400, "数据校验出现问题").put("data", errorMap);
    }


    @ResponseBody
    @ExceptionHandler(value = Throwable.class)
    public BaseResult handleValidException(Throwable e) {

        log.error("系统出现问题: {},异常类型: {}", e.getMessage(), e.getClass());

        return BaseResult.error();
    }


}
